<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts';
import { defineComponent, shallowRef } from 'vue';
import macaronsTheme from '@/styles/echarts/theme/macarons'; // echarts theme
import resize from './mixins/resize';
import { performanceData } from '@/api/homePage.js'
import eventBus from '@/utils/eventBus'


export default defineComponent({
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      chart: null
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler (val) {
        this.setOptions(val);
      }
    }
  },
  mounted () {
    eventBus.on('typeChange', (msg) => {
      console.log('圖表收到消息', msg)
      if (msg.chart == 'area') {
        this.getPerformanceData(msg.type)
      }
    })
    this.$nextTick(() => {
      this.initChart();
      // this.getPerformanceData()
    });
  },
  beforeUnmount () {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    getPerformanceData (type = 1) {
      performanceData({ type: type }).then((res) => {
        console.log(res)
        this.setOptions(res.data.uid, res.data.value)
      })
    },
    initChart () {
      this.chart = shallowRef(echarts.init(this.$el, macaronsTheme));
      this.getPerformanceData()
      // this.setOptions(this.chartData);
    },
    setOptions (xdata, ydata) {
      this.chart.setOption({
        xAxis: {
          data: xdata,
          boundaryGap: false,
          axisTick: {
            show: false
          },
          type: 'category'
        },
        grid: {
          left: 10,
          right: 10,
          bottom: 20,
          top: 30,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        yAxis: {
          type: 'value',
          axisTick: {
            show: false
          }
        },
        legend: {
          data: ['expected', 'actual']
        },
        series: [{
          itemStyle: {
            color: '#1270ff'
          },
          lineStyle: {
            color: '#1270ff',
            width: 2
          },
          smooth: false,
          type: 'line',
          data: ydata,
          animationDuration: 2800,
          animationEasing: 'cubicInOut',
          areaStyle: {
            normal: {
              color: '#cbe0ff'
            }
          },
        }],
      });
    }
  }
});
</script>
